package servlets;

import java.io.IOException;
import java.util.Enumeration;

import javax.jms.JMSException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ReaderDAO;
import dao.hibernate.ReaderDAOHibernateImpl;

import model.Reader;

/**
 * Servlet implementation class LoginServlet.
 */
public class LoginServlet extends HttpServlet {
    /** Serial version UID. */
    private static final long serialVersionUID = 1L;

    /** DAO to modify readers in the database. */
    private ReaderDAO readerDAO;

    /**
     * Initializes the servlet.
     *
     * @param config  configuration data of the servlet
     * @throws ServletException  if there is any problem
     */
    @Override
    public void init(final ServletConfig config) throws ServletException {
        super.init(config);

        readerDAO = new ReaderDAOHibernateImpl();
    }

    /**
     * Log out a user.
     *
     * Remove all the attributes in the session and return the login view.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doGet(HttpServletRequest request,
     *                           HttpServletResponse response)
     */
    @Override
    @SuppressWarnings("unchecked")
    protected void doGet(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        Reader reader = (Reader) request.getSession().getAttribute("reader");
        //update the reader in the database
        readerDAO.updateReader(reader);
        try {
            //close all the connections of the reader
            reader.closeConnections();
        } catch (JMSException e) {
            //connections already closed?
            System.err.println("Error closing connections of reader "
                               + reader.getClientId() + ": " + e);
        }
        //delete all the attributes of the session
        Enumeration<String> attrNames = (Enumeration<String>)
                request.getSession().getAttributeNames();
        String attrName;
        while (attrNames.hasMoreElements()) {
            attrName = attrNames.nextElement();
            request.getSession().removeAttribute(attrName);
        }
        getServletContext().getRequestDispatcher(
                "/jsp/index.jsp").forward(request, response);
    }

    /**
     * Read the login parameters and, if they are correct, put the corresponding
     * user in the session and let him access the application.
     *
     * @param request  HTTP request
     * @param response  HTTP response
     * @throws ServletException  if there is any problem
     * @throws IOException  if there is any problem
     * @see HttpServlet#doPost(HttpServletRequest request,
     *                            HttpServletResponse response)
     */
    @Override
    protected void doPost(final HttpServletRequest request,
            final HttpServletResponse response)
            throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //TODO: real login
        Reader reader = readerDAO.getReader(username, password);
        //if the login is correct, log the reader in
        if (reader != null)  {
                //get the brokers to publish to
                reader.requestBroker();

            request.getSession().setAttribute("reader", reader);
            getServletContext().getRequestDispatcher(
                    "/jsp/readerMainView.jsp").forward(request, response);
        } else { //if the login is incorrect, forward to login view
            getServletContext().getRequestDispatcher(
                    "/jsp/index.jsp").forward(request, response);
        }

    }

}
